package server;

import entity.User;
import service.UserServiceImpl;
import utils.ServerConfig;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.List;

//服务器退出端口
public class ServerExit implements Runnable{
    private UserServiceImpl userService;
    private  List<ServerOutPut> list;

    public void setList(List<ServerOutPut> list) {
        this.list = list;
    }

    public ServerExit(UserServiceImpl userService) {
        this.userService=userService;
    }


    @Override
    public void run() {
        DatagramSocket socket = null;
        User user = new User();
        try {
            //接收客户端包
            socket = new DatagramSocket(ServerConfig.serverConfig("ServerExitPort"));
        } catch (SocketException e) {
            e.printStackTrace();
        }
        try {
            while (true){
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(packet);
                user.setPort(packet.getAddress().toString());
                user.setName(new String(packet.getData(),0, packet.getLength()));
                user.setServerport(userService.findByPort(user.getPort()).getServerport());
                System.out.println("Exit=="+user.getPort()+""+user.getName());
                //删除mysql用户信息
                userService.delete(user);
                for (ServerOutPut serverOutPut:list) {
                    if(user.getServerport()==serverOutPut.getPort()){
                        //停止该用户的服务端空号
                        serverOutPut.setOn(true);
                        System.out.println(user.getServerport()+"停止");
                        break;
                    }
                }
                //list.forEach(s->System.out.println("--"+s.getName()));
            }
        } catch (Exception e) {
            System.out.println("进程停止");
        }finally {
            socket.close();
        }
    }
}
